package utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

/**
 * 文件的操作
 *
 * @author: xiuwei
 * @version:
 */
public class FileUtils {


	public static String getResourcesPath() {
		String path = FileUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		try {
			path = java.net.URLDecoder.decode(path, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (path.contains(".jar!/")) {
			path = path.substring(0, path.indexOf(".jar!/") + 3);
		}
		File file = new File(path);
		if (file.isDirectory()) {
			return file.getAbsolutePath();
		} else {
			return file.getParent().replace("file:\\", "").replace("file:", "");
		}
	}


	public static String getResourcesPath(Class clazz) {
		String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
		try {
			path = java.net.URLDecoder.decode(path, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (path.contains(".jar!/")) {
			path = path.substring(0, path.indexOf(".jar!/") + 3);
		}
		File file = new File(path);
		if (file.isDirectory()) {
			return file.getAbsolutePath();
		} else {
			return file.getParent().replace("file:\\", "").replace("file:", "");
		}
	}


	public static void write2File(String path, String fileName, String context) throws IOException {
		File directory = new File(path);
		if (!directory.exists()) {
			directory.mkdirs();
		}
		File file = new File(path + "/" + fileName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		PrintStream stream = new PrintStream(file);
		stream.print(context);
		stream.flush();
		stream.close();
	}
}
